package qqserver.service;

import qqcommon.Message;
import qqcommon.MessageType;
import utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

/**
 * @author DCSGO
 * @version 1.0
 * 向所有在线用户推送消息
 */
public class SendToAllService implements Runnable {
    private final DateTimeFormatter dtf;

    @Override
    public void run() {
        while (true) {
            System.out.println("请输入要推送的消息(exit 退出推送服务)：");
            String news = Utility.readString(300);
            if (news.equals("exit")) {
                break;
            }
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            message.setSender("服务器");
            message.setSendTime(dtf.format(LocalDateTime.now()));
            message.setContent(news);
            ArrayList<Socket> allClientSockets = ManageServerConnectClientThreads.getAllClientSockets();
            for (Socket s : allClientSockets) {
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public SendToAllService() {
        dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 E HH:mm:ss");
    }
}
